package com.ying.timed.service.impl;

import cn.hutool.core.date.DateUtil;
import com.ying.common.entity.Response;
import com.ying.timed.common.TimedEnum;
import com.ying.timed.config.CronTaskRegistrar;
import com.ying.timed.config.SchedulingRunnable;
import com.ying.timed.dao.TimedDao;
import com.ying.timed.entity.Timed;
import com.ying.timed.entity.TimedQuery;
import com.ying.timed.service.TimedService;
import com.ying.timed.utils.CronUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class TimedServiceImpl implements TimedService {

    @Autowired
    private TimedDao timedDao;
    @Autowired
    private CronTaskRegistrar cronTaskRegistrar;
    private static final Logger logger = LoggerFactory.getLogger(TimedServiceImpl.class);

    @Override
    public Response insertTimed(Timed timed) {
        Date date = new Date();
        timed.setJobStatus(0);
        timed.setCreateTime(date);
        timed.setUpdateTime(date);
        int i = timedDao.insertSelective(timed);
        if (i < 0) {
            return new Response().failure("新增失败");
        } else {
            if (timed.getJobStatus().equals(TimedEnum.NORMAL.getIndex())) {
                SchedulingRunnable task = new SchedulingRunnable(timed.getBeanName(), timed.getMethodName(), timed.getMethodParams());
                cronTaskRegistrar.addCronTask(task, timed.getCronExpression());
            }
        }
        return new Response().success("新增成功");
    }

    @Override
    public Response updateTimed(Timed timed) {
        Timed existTimed = timedDao.selectByPrimaryKey(timed.getJobId());
        timed.setUpdateTime(new Date());
        int i = timedDao.updateByPrimaryKeySelective(timed);
        if (i < 0) {
            return new Response().failure("编辑失败");
        } else {
            //先移除再添加
            if (timed.getJobStatus().equals(TimedEnum.NORMAL.getIndex())) {
                SchedulingRunnable task = new SchedulingRunnable(existTimed.getBeanName(), existTimed.getMethodName(), existTimed.getMethodParams());
                cronTaskRegistrar.removeCronTask(task);
            }
            if (timed.getJobStatus().equals(TimedEnum.NORMAL.getIndex())) {
                SchedulingRunnable task = new SchedulingRunnable(timed.getBeanName(), timed.getMethodName(), timed.getMethodParams());
                cronTaskRegistrar.addCronTask(task, timed.getCronExpression());
            }
        }
        return new Response().success("编辑成功");
    }

    @Override
    public Response deleteTimed(Timed timed) {
        int i = timedDao.deleteByPrimaryKey(timed.getJobId());
        if (i < 0) {
            return new Response().failure("删除失败");
        } else {
            if (timed.getJobStatus().equals(TimedEnum.NORMAL.getIndex())) {
                SchedulingRunnable task = new SchedulingRunnable(timed.getBeanName(), timed.getMethodName(), timed.getMethodParams());
                cronTaskRegistrar.removeCronTask(task);
            }
        }
        return new Response().success("删除成功");
    }

    @Override
    public Response updateStatus(Timed timed) {
        if (timed.getJobStatus().equals(TimedEnum.NORMAL.getIndex())) {
            SchedulingRunnable task = new SchedulingRunnable(timed.getBeanName(), timed.getMethodName(), timed.getMethodParams());
            cronTaskRegistrar.addCronTask(task, timed.getCronExpression());
            timedDao.updateByPrimaryKeySelective(timed);
        } else {
            SchedulingRunnable task = new SchedulingRunnable(timed.getBeanName(), timed.getMethodName(), timed.getMethodParams());
            cronTaskRegistrar.removeCronTask(task);
            timedDao.updateByPrimaryKeySelective(timed);
        }
        return new Response().success("状态更改成功");
    }

    @Override
    public Response selectTimed() {
        TimedQuery timedQuery = new TimedQuery();
        List<Timed> timedList = timedDao.selectByQuery(timedQuery);
        return new Response().success(timedList);
    }

    @Override
    public Response executeTask(Timed timed) {
        Date date = DateUtil.date();
        date.setTime(date.getTime() + 2*1000);
        String now = DateUtil.formatDateTime(date);
        String cron = CronUtils.getCron(date);
        logger.info("手动执行一次的时间为：{}，表达式为：{}", now, cron);
        SchedulingRunnable task = new SchedulingRunnable(timed.getBeanName(), timed.getMethodName(), timed.getMethodParams());
        cronTaskRegistrar.addCronTask(task, cron);
        return new Response().success("手动执行一次成功");
    }

    public static void main(String[] args) {
        Date date = DateUtil.date();
        date.setTime(date.getTime() + 2*1000);
        String now = DateUtil.formatDateTime(date);
        String cron = CronUtils.getCron(date);
        System.out.println(date);
        System.out.println(now);
        System.out.println(cron);
    }
}
